package com.example.oj.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.oj.entity.User;
import com.example.oj.service.UserService;
import com.example.oj.mapper.UserMapper;
import com.example.ojcommon.common.ErrorCode;
import com.example.ojcommon.constant.CommonConstant;
import com.example.ojcommon.constant.UserConstant;
import com.example.ojcommon.enums.UserRoleEnum;
import com.example.ojcommon.exception.BusinessException;
import com.example.oj.entity.dto.user.UserAddRequest;
import com.example.oj.entity.dto.user.UserLoginRequest;
import com.example.oj.entity.dto.user.UserQueryRequest;
import com.example.oj.entity.dto.user.UserUpdateRequest;
import com.example.oj.entity.vo.UserVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author mingjianyun
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-12-26 11:18:34
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

  @Resource
  private UserMapper userMapper;

  @Value("${files.images.host}")
  private String host;

  @Value("${files.images.path}")
  private String path;

  /**
   * 盐值，混淆密码
   */
  private static final String SALT = "md5fe";

  @Override
  public long userRegister(UserAddRequest request) {
    String nickname = request.getNickname();
    String username = request.getUsername();
    String password = request.getPassword();
//        MultipartFile file = request.getImage();
    // 1. 校验
    if (StringUtils.isAnyBlank(username, password, nickname)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
    }
    if (username.length() < 8) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
    }
    if (password.length() < 8) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
    }
    synchronized (username.intern()) {
      // 2. 账户不能重复
      QueryWrapper<User> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("username", username);
      boolean exists = userMapper.exists(queryWrapper);
      if (exists) {
        throw new BusinessException(ErrorCode.USER_EXISTED_ERROR);
      }
      // 3. 加密
      String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
      // 4. 插入数据
      User user = new User();
      user.setUsername(username);
      user.setPassword(encryptPassword);
      user.setNickname(nickname);
      user.setUserRole(UserRoleEnum.USER.getValue());
      boolean saveResult = this.save(user);
      if (!saveResult) {
        throw new BusinessException(ErrorCode.DATABASE_ERROR, "注册失败，数据库错误");
      }
      return user.getId();
    }
  }

  /**
   * 文件上传，返回文件保存路径
   *
   * @return
   */
  @Override
  public String uploadFile(MultipartFile file) {
    //防止文件名重复
    String filename = UUID.randomUUID() + "-" + file.getOriginalFilename();
    //文件保存目录路径
    String parentPath = System.getProperty("user.dir") + File.separator + path;
    if (!FileUtil.exist(parentPath)) {
      FileUtil.mkdir(parentPath);
    }
    //用户文件路径
    String filepath = parentPath + File.separator + filename;
    try {
      FileUtil.writeFromStream(file.getInputStream(), filepath);
    } catch (IOException e) {
      throw new BusinessException(ErrorCode.FILE_UPLOAD_ERROR);
    }
    //用户文件访问路径
//    String urlPath = host + File.separator + filepath;
    return filepath;
  }

  @Override
  public UserVO userLogin(UserLoginRequest loginRequest, HttpServletRequest request) {
    String username = loginRequest.getUsername();
    String password = loginRequest.getPassword();
    User user = doLogin(username, password);
    // 记录用户的登录态 TODO 登录状态保存信息
    request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
    return getUserVO(user);
  }

  public User doLogin(String username, String password) {
    // 1加密
    String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
    // 2查询用户 TODO username索引设计
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username", username);
    queryWrapper.eq("password", encryptPassword);
    User user = userMapper.selectOne(queryWrapper);
    if (user == null) {
      // 用户不存在
      throw new BusinessException(ErrorCode.USER_NOT_EXISTED_ERROR);
    }
    return user;
  }

  @Override
  public boolean userLogout(HttpServletRequest request) {
    if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
    }
    // 移除登录态
    request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
    return true;
  }

  @Override
  public User getLoginUser(HttpServletRequest request) {
    // 先判断是否已登录null
    User currentUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
    if (currentUser == null || currentUser.getId() == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    return currentUser;
  }

  @Override
  public boolean isAdmin(User user) {
    return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
  }

  @Override
  public UserVO getUserVO(User user) {
    UserVO userVO = new UserVO();
    userVO.setId(user.getId());
    userVO.setUsername(user.getUsername());
    userVO.setNickname(user.getNickname());
    userVO.setCreateTime(user.getCreateTime());
    userVO.setUserRole(UserRoleEnum.valueOf(user.getUserRole()));
    userVO.setSubmitNum(user.getSubmitNum());
    userVO.setAcceptNum(user.getAcceptNum());
    UserVO temp = userMapper.selectQuestionNum(user.getId());
    userVO.setAcceptNum1(temp.getAcceptNum1());
    userVO.setAcceptNum2(temp.getAcceptNum2());
    userVO.setAcceptNum3(temp.getAcceptNum3());
    userVO.setSubmitNum1(temp.getSubmitNum1());
    userVO.setSubmitNum2(temp.getSubmitNum2());
    userVO.setSubmitNum3(temp.getSubmitNum3());
    return userVO;
  }

  @Override
  public List<UserVO> getUserVO(List<User> userList) {
    if (CollectionUtils.isEmpty(userList)) {
      return new ArrayList<>();
    }
    return userList.stream().map(this::getUserVO).collect(Collectors.toList());
  }

  @Override
  public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
    if (userQueryRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
    }
    String username = userQueryRequest.getUsername();
    String nickname = userQueryRequest.getNickname();
    Integer userRole = userQueryRequest.getUserRole();
    String sortField = userQueryRequest.getSortField();
    String sortOrder = userQueryRequest.getSortOrder();

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    //判断id是否为空，不为空在sql语句中添加id = #{id}
    queryWrapper.eq(username != null, "username", username);
    //同理，如果nickname不为空，那就再sql语句中拼接一个nickname = #{nickname}
    queryWrapper.eq(ObjectUtils.isNotEmpty(nickname), "nickname", userRole);
    queryWrapper.like(ObjectUtils.isNotEmpty(userRole), "userRole", userRole);
    queryWrapper.orderBy(ObjectUtils.isNotEmpty(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
    return queryWrapper;
  }

  @Override
  public Integer updateUser(UserUpdateRequest userUpdateRequest) {
    User user = new User();
    Long id = userUpdateRequest.getId();
    String password = userUpdateRequest.getPassword();
    String nickname = userUpdateRequest.getNickname();
//    String image = userUpdateRequest.getImage();
    boolean b = false;
    user.setId(id);
    if (password != null && !password.isEmpty()) {
      user.setPassword(password);
      b = true;
    }
    if (nickname != null && !nickname.isEmpty()) {
      user.setNickname(nickname);
      b = true;
    }
//    if (image != null && !image.isEmpty()) {
//      user.setImage(image);
//      b = true;
//    }
    if (b) {
      return userMapper.updateById(user);
    } else {
      return 0;
    }
  }

  @Override
  public void updateUserSubmitNum(Long id) {
    userMapper.updateUserSubmitNum(id);
  }


}




